import getpath
import os
import logging
import csv
import myglobal
import config_json
from delegates import EditDelegateQt,DateTimeEditDelegateQt,DoubleViewDelegate,FloatEditDelegateQt
import sample
from PyQt5 import QtWidgets,QtCore
from DlgYanghua import DlgYanghua
import openpyxl
import re
import logging
from mydb import MyDB_Base
class SampleWeigt(sample.Sample):
    def __init__(self):
        super().__init__()
        self.V1=None
        self.V2=None
        self.m2=None
        self.m1=None
        self.m0=None
        self.m3=None
        self.m4=None
        self.m5=None
        self.item=None
        pass
class MyDb(MyDB_Base):
    def addOne(self):
        n=SampleWeigt()
        n.sampleid="001"
        return n
    def __init__(self,mainw):
        super().__init__(mainw)
        self.doublefmt="%.6f"
        self.properties = [
            {"ele":None,"delegate":self.editDelegate,'width':130,'attr': "sampleid",'visible':True,  'header': "样品中心编号"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "mass",'visible':True,  'header': "试料质量m"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "V1",'visible':True,  'header': "定容体积V1"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "V2",'visible':True,  'header': "分取体积V2"},
            {"ele":None,"delegate":self.floatEdit,'width':100,'attr': "m2",'visible':True,  'header': "坩埚及沉淀质量m2"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "m1",'visible':True,  'header': "坩埚质量m1"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "m0",'visible':True,  'header': "空白质量m0"},
            {"ele":None,"delegate":self.floatEdit,'width':100,'attr': "m3",'visible':True,  'header': "溶液中残余质量m3"},
            {"ele":None,"delegate":self.floatEdit,'width':90,'attr': "m4",'visible':True,  'header': "干扰物质量m4"},
            {"ele":None,"delegate":self.floatEdit,'width':80,'attr': "m5",'visible':True,  'header': "干扰物质量m5"},
            {"xishu":None,"ele":config_json.setting["weight"]["ele"],"delegate":self.editDelegate,'width':80,'attr': "item",'visible':True,  'header': config_json.setting["weight"]["ele"]},
            {"ele":None,"delegate":self.editDelegate,'width':80,'attr': "beizhu",'visible':True,  'header': "备注"},
        ]
    def contextMenuEvent(self,event):
        menu = QtWidgets.QMenu(self.mainw)
        calcAction = menu.addAction("计算")
        action = menu.exec_(self.mainw.mapToGlobal(event.pos()))
        if action == calcAction:
            self.calc()
    def calc(self):
        for one in self.mainw.appends:
            k=one[0]
            w=one[1]
            l=w.l.text()
            v=w.t.text()
            config_json.setting["append"]["weight"][k]=[l,v]
        n=len(self.mainw.objects2)
        for i in range(n):
            try:
                o=self.mainw.objects2[i]
                m2=myglobal.myfloat(o.m2)
                m1=myglobal.myfloat(o.m1)
                m0=myglobal.myfloat(o.m0)
                m3=myglobal.myfloat(o.m3)
                m4=myglobal.myfloat(o.m4)
                m5=myglobal.myfloat(o.m5)
                mass=myglobal.myfloat(o.mass)
                V1=myglobal.myfloat(o.V1)
                V2=myglobal.myfloat(o.V2)
                if V2==0:
                    V1=1
                    V2=1
                xishu=myglobal.myfloat(self.mainw.appends[0][1].t.text())
                o.item=(m2-m1-m0+m3-m4-m5)/mass*V1/V2*xishu*100
            except ZeroDivisionError:
                pass
        # self.mainw.refresh_grid2()
    def showColumnMenu(self, pos):
        logging.info("showCloumnMenu")
        logging.info(pos)
        it = self.mainw.ui.tableView_report.columnAt(pos.x())  # 根据鼠标坐标获取列号
        logging.info(it)
        # self.title = ["id", "time", "sampleid", "mass", "volume"]
        # title = self.model2.headerData(it, Qt.Horizontal)
        if self.properties[it]["ele"]!=None:
            menu =QtWidgets.QMenu()
            # self.yanghua)
            menu.addAction("项目", lambda val=pos: self.yanghua(val))
            # self.yanghua)
            # menu.addAction("移除", lambda val=pos: self.selectChannel(val))
            pos = self.mainw.ui.tableView_report.horizontalHeader().viewport().mapToGlobal(pos)
            return menu.exec_(pos)
    def yanghua(self, pos):
        logging.info("yanghua")
        logging.info(pos)
        it = self.mainw.ui.tableView_report.columnAt(pos.x())  # 根据鼠标坐标获取列号
        logging.info(it)
        # self.title = ["id", "time", "sampleid", "mass", "volume"]
        one= self.properties[it]#.ele# model2.headerData(it, Qt.Horizontal)
        logging.info(one)
        d = DlgYanghua()
        d.ui.lineEdit_ele.setText(one["ele"])
        tit = one["header"].split(' ')[0]
        # d.ui.edit_yanghua.setText(tit)
        # d.ui.edit_xishu.setText(str(one.get("xishu")))
        d.setWindowTitle("更改项目")
        d.ui.edit_yanghua.setVisible(False)
        d.ui.edit_xishu.setVisible(False)
        d.ui.label.setVisible(False)
        d.ui.label_2.setVisible(False)
        r = d.exec_()
        if r == 1:
            self.changeYanghua(
                it, d.ui.lineEdit_ele.text(),d.ui.edit_yanghua.text(), d.ui.edit_xishu.text())
        else:
            pass

    def changeYanghua(self, i, ele,yanghua, xishu):
        logging.info(str(i)+","+yanghua+","+str(xishu))
        config_json.setting["weight"]["ele"]=ele
        # self.properties[i]["xishu"] =myglobal.myfloat(xishu)
        # titles = self.properties[i]["header"].split(" ")
        newtitle=ele #" ".join([yanghua, titles[1]])
        self.properties[i]["header"]= newtitle
        self.properties[i]["ele"]= ele
        self.mainw.chks[i].setText(newtitle)
        self.mainw.refresh_grid2()
        # self.model.setHeaderData(i, Qt.Horizontal, self.fields[i]["title"])
        # self.model2.setHeaderData(i, Qt.Horizontal, self.fields[i]["title"])

    def import_text_bytitle(self, txt):
        logging.info(txt)
        data = []
        for row in txt.split("\n"):
            # logging.info(row)
            data.append(row.split("\t"))
        title = data[0]
        data = data[1:]
        logging.info(title)
        for f in self.properties:
            f["at"] = myglobal.in_list(f["header"],title )
        if len(self.mainw.objects)>0:
            num=self.mainw.objects[-1].num+1
        else:
            num=0
        r=[]
        for one in data:
            # logging.info("=====================")
            # logging.info(one)
            if len(one) < 2:
                continue
            fs = []
            vs = []
            for f in self.properties:
                if f["at"] != -1:
                    fs.append( f["attr"])
                    vs.append(one[f["at"]] )
            print(fs,vs)
            s=SampleWeigt()
            for i in range(len(fs)):
                setattr(s,fs[i],vs[i])
            s.num=num
            if s.sampleid!="":
                r.append(s)
        print(r)
        return r
    def getDataDays(self, v):
        filename=config_json.setting['database']
        data=getdata(filename)
        return self.toObjects(data) 
    def toObjects(self,samples):        
        objs=[]
        num=0
        for one in samples:
            s=sample.Sample()
            s.num=num
            s.sampleid=one["sampleid"]
            logging.info(s.sampleid)
            s.mass=one["mass"]
            s.volume=one["volume"]
            s.items={}
            for i in range(len(one["items"])): #one in one["items"]:
                s.items[one["items"][i]]=one["conc"][i]
            objs.append(s)
            num+=1
        self.resetProperties(s.items)
        return objs  
    def checkBoth(self):
        name = []
        for f in self.properties:
            if f["visible"]:
                logging.info(name)
                if (f["ele"]!=None):
                    if(f["ele"][0] in name):
                        QMessageBox.information(self, "", "不能同时选择一个元素的两个通道")
                        return True
                    else:
                        name.append(f["ele"][0])
        return False
    def remove_pingxing(self,a):
        for i in range(len(a)):
            if a[i]=="_":
                return a[:i]        
        return a        
    def checkSingle(self):
        n = len(self.mainw.objects2)
        r={}
        for row_idx in range(n):
            record = self.mainw.objects2[row_idx]
            name=str(record.sampleid)
            if config_json.setting["pingxing"]==1:
                name=self.remove_pingxing(name)
            if re.match(self.mainw.sample_name_pattern,name.strip())!=None:# name.strip()[0:0+2]=="23":
                if r.get(name)!=None:
                    r[name]+=1
                else:
                    r[name]=1
        logging.info(r)
        all=[]
        for k in r.keys():
            if r[k]==1:
                all.append(k)
        if len(all)==0:
            return ""
        else:
            return ",".join(all)        
    def lims(self):
        if self.checkBoth():
            return
        ffbh = self.mainw.ui.cmb_ffbh.text()
        syy = self.mainw.ui.cmb_syy.text()
        ysry = self.mainw.ui.cmb_ysry.text()
        syyqm = self.mainw.ui.cmb_syyqm.text()
        yqbh = config_json.setting["yqbh"]
        queren = ""
        single=self.checkSingle()
        if single!="":
            queren = queren+"样品(%s)没有平行样!!!\n" % single 
            queren = queren+"\n"
        queren = queren+"方法编号(%s)\n" % ffbh
        queren = queren+"实验员(%s)\n" % syy
        queren = queren+"一审(%s)\n" % ysry
        queren = queren+"实验员签名(%s)\n" % syyqm
        queren = queren+"仪器编号(%s)\n" % yqbh
        logging.info(["ejff",config_json.setting["ejff"]])
        ejff= self.mainw.ui.cmb_ff2.text()
        ejfxjs= self.mainw.ui.cmb_js2.text()
        if config_json.setting["ejff"]==1 and ejff!="" and ejfxjs!="":
            queren = queren+"二级方法(%s)\n" % ejff
            queren = queren+"二级分析技术(%s)" % ejfxjs
        r = QtWidgets.QMessageBox.question(
            self.mainw, '输出', queren, QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.Yes)
        if r == QtWidgets.QMessageBox.No:
            return            
        if len(yqbh)>4:
            yqbh=yqbh[-4:]
        if self.mainw.ui.lineEdit_filename.text() == "":
            file_name = yqbh + "_" + myglobal.timestr()
        else:
            file_name = yqbh+"_"+self.mainw.ui.lineEdit_filename.text()
        path = config_json.setting["output_folder"]
        filepath = os.path.join(path, file_name)
        self.output_xlsx(filepath)

    def output_xlsx(self, filepath):
        n =len(self.mainw.objects2)
        if n == 0:
            return
        filepath = filepath + ".xlsx"
        # 1. 创建文件对象（指定文件名，模式，编码方式）a模式 为 下次写入在这次的下一行
        fname=os.path.join(getpath.getpath(),"weight_t.xlsx")
        wb=openpyxl.load_workbook(filename=fname)
        ws = wb.worksheets[0]
        for row_idx in range(n):
            record = self.mainw.objects2[row_idx]
            sampleid=self.remove_pingxing(record.sampleid)
            row = [sampleid,"","",record.mass,"",record.V1,record.V2,record.m2,record.m1,record.m0,record.m3,record.m4,record.m5]
            for f in self.properties:
                if f["visible"] and f["ele"]!=None:
                    v=getattr(record,f["attr"])
                    xishu=f.get("xishu")
                    if xishu:
                        v=myglobal.myfloat(v)*xishu
                    row.append(v)
            row.append(record.beizhu)
            ws.append(row)
        ffbh = self.mainw.ui.cmb_ffbh.text()
        syy = self.mainw.ui.cmb_syy.text()
        ysry = self.mainw.ui.cmb_ysry.text()
        yqbh = config_json.setting["yqbh"]
        config_json.setting["yqbh"]=yqbh
        syyqm = self.mainw.ui.cmb_syyqm.text()
        row = ["ffbh&" + ffbh, "", "", "", ""]
        ws.append(row)
        row = ["syy&" + syy, "", "", "", ""]
        ws.append(row)
        row = ["ysry&" + ysry, "", "", "", ""]
        ws.append(row)
        row = ["syyqm&" + syyqm, "", "", "", ""]
        ws.append(row)
        ff2= self.mainw.ui.cmb_ff2.text()
        js2= self.mainw.ui.cmb_js2.text()
        if config_json.setting["ejff"]==1 and ff2 != "" and js2 != "":
            ws.append(["ejff&" + ff2,"", "", "", ""])  # todo
            ws.append(
                ["ejfxjs&" + js2, "", "", "", ""])
        row = ["yqbh&" + yqbh, "", "", "", ""]
        ws.append(row)
        ws["N3"]=config_json.setting["weight"]["ele"]
        ws["B1"]=yqbh
        ws["H1"]=yqbh
        ws["K1"]=syy
        ws["N1"]=ysry
        for one in self.mainw.appends:
            k=one[0]
            w=one[1]
            l=w.l.text()
            v=w.t.text()
            row = [k+"&" + v,l, "", "", ""]
            ws.append(row)
            config_json.setting["append"]["weight"][k]=[l,v]
        ws.column_dimensions['A'].width = 30.0
        wb.save(filepath)
        scrollbar = self.mainw.ui.textEdit.verticalScrollBar()
        scrollbar.setSliderPosition(scrollbar.maximum())                      
        self.mainw.ui.textEdit.insertPlainText(filepath + "\n")
        scrollbar = self.mainw.ui.textEdit.verticalScrollBar()
if __name__=="__main__":
    file = os.path.join(getpath.getpath(), "930.csv")
    config_json.read_setting()
    config_json.setting['database'] = file
    db = MyDb(None)
    objs=db.getDataDays(200)
    for obj in objs:
        print(obj.sampleid)
        for one in obj.items.keys():
            print(one[0]+"_"+one[1],getattr(obj,one[0]+"_"+one[1]))       